package com.x.erp.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.x.erp.model.CarOrder;
import com.x.framework.dao.BaseDao;

/**
 * 预订信息DAO
 */
@Repository
public class CarOrderDao extends BaseDao {

	private final static String selectOrderListSql = "SELECT " +
			"eco.*, " +
			"eu.USER_NAME, " +
			"bp.PROVINCE_NAME, " +
			"bc.CITY_NAME " +
			"FROM " +
			"ERP_CAR_ORDER eco  " +
			"JOIN ERP_USER eu ON eco.ORDER_DEAL_USER_ID = eu.USER_ID " +
			"LEFT JOIN BASE_PROVINCE bp ON eco.PROVINCE_ID = bp.PROVINCE_ID " +
			"LEFT JOIN BASE_CITY bc ON eco.CITY_ID = bc.CITY_ID " +
			"WHERE 1=1 ";
	/**
	 * 查询预订列表
	 * @param order
	 * @return
	 * @throws Exception
	 */
	public List<CarOrder> selectCarOrderList(CarOrder order) throws Exception{
		StringBuilder sql = new StringBuilder(selectOrderListSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, order);
		return this.queryForList(sql.toString(), CarOrder.class, params);
	}

	private final static String selectOrderNumSql = "SELECT COUNT(eco.ORDER_ID) FROM ERP_CAR_ORDER eco WHERE true ";
	/**
	 * 查询预订数量
	 * @param order
	 * @return
	 * @throws Exception
	 */
	public int selectCarOrderNum(CarOrder order) throws Exception{
		StringBuilder sql = new StringBuilder(selectOrderNumSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, order);
		return this.queryForInt(sql.toString(), params);
	}

	/**
	 * 查询条件
	 * @param sql
	 * @param params
	 * @param order
	 */
	private void searchCondition(StringBuilder sql, List<Object> params, CarOrder order) {
		if(order != null) {
			if(StringUtils.isNotEmpty(order.getOrderId())){
				sql.append("AND eco.ORDER_ID = ? ");
				params.add(order.getOrderId());
			}
			if(StringUtils.isNotEmpty(order.getCarId())){
				sql.append("AND eco.CAR_ID = ? ");
				params.add(order.getCarId());
			}
		}
	}
}
